﻿var gUserId = -1;
var gDeskId = -1;
var request = null;
var mainLoopRequest = null;
var desk2DivId = new Array();
var gameStatus = 0; //0: not begin, 1: in playing 2: ended
var isFirstPlayer = false;
var selectedCards = new Array();

// constants
var cardColors = ["方块", "梅花", "红桃", "黑桃"];
// constants end

function debugCmd(prefix, cmd, args) {
	var str = prefix + cmd + ':' + args.join(',');
	_("right_side").innerHTML = str + '<br/>' + _("right_side").innerHTML;
}

// Send AJAX POST request <URL>?cmd=<CMD>&args=<ARGS>
function send(str) {
    debugCmd('>> ', 'ori cmd str', [str]);
    var cmd = str.split(",", 1)[0];
    var args = str.slice(cmd.length + 1);
    debugCmd('>> ', cmd, [args]);
    var params = 'cmd=' + cmd + '&args=' + args
    request = getXMLHttpRequest();
    request.onreadystatechange = cmdListHandler;
    request.open('POST', '/cmd', true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.send(params);
    _("game_status").innerHTML = "";
    _('temp_pane').innerHTML = "";
}

function cmdHandler(str) {
    var cmd = str.cmd;
    var args = str.args;
	debugCmd('<< ', cmd, args);

    if(cmd == 'ACK' ) {

    } else if(cmd == 'DISPATCH_CARD') {
        for(var i = 0; i < args.length; i++){
        	showCard(args[i]);
        }
    } else if(cmd == 'REMOVE_CARD') {
    	var card = _('card_'+args[0]);
    	_('hand').removeChild(card);
    } else if(cmd == 'EQUIP_CARD'){
    	var deskId = args[0];
    	var cardId = args[1][0];
    	var cardDesc = args[1][1] + args[1][2] + args[1][3];
    	var cardType = args[1][4];
    	var card = createElement('div', ['id', 'card_'+cardId]);
    	card.innerHTML = cardDesc;
    	var divId = (deskId == gDeskId ? '' : '_'+deskId);
    	if(cardType == '3'){
    		_('judge'+divId).appendChild(card);
    	} else if(cardType == '4' || cardType == '5'){
    		_('horse'+divId).appendChild(card);
    	} else if(cardType == '6'){
    		_('weapon'+divId).appendChild(card);
    	} else if(cardType == '7'){
    		_('horse'+divId).appendChild(card);
    	} else {
    		alert('Cannot equip card ' + cardDesc);
    	}
    } else if(cmd == 'UNEQUIP'){
    	var deskId = args[0];
    	var cardId = args[1];
    	var card = _('card+'+cardId);
    	card.parentNode.removeChild(card);
    } else if(cmd == 'SET_HP') {
    	var deskId = args[0];
    	var hp = args[1];
    	if(deskId == gDeskId)
    		_('hp').innerHTML = 'HP值 '+hp;
    	else
    		_("hp_"+deskId).innerHTML = 'HP值 '+hp;
    }
    else if(cmd == 'REQ_TARGET') {
    	// TODO 所有others按钮可用
    	_("game_status").innerHTML = "请选一个目标";
    	//_("btn_ok").setAttribute('onclick',
    	//		'send("SET_TARGET," + gDeskId + "," + getSelectedDeskIds())')
    }
    else if(cmd == 'SET_SKILL') {
        _("skill_0").setAttribute('onclick',
                'send("USE_SKILL,' + gDeskId + ',' + args[1] + '");');
        _("skill_0").setAttribute('data-skill-id', args[1]);
        _("skill_0").innerHTML = args[2];
    }
    else if(cmd == 'REQ_ACTION') {
        _("game_status").innerHTML = args[0];
        this.reqTargetWithCard = true;
    }
    else if(cmd == 'REQ_CARD_TARGET') {
    	_("game_status").innerHTML = args[0];
        this.reqTargetWithCard = true;
    }
    else if(cmd == 'REQ_CARD') {
    	_("game_status").innerHTML = args[0];
        this.reqTargetWithCard = false;
    }
    else if(cmd == 'YOU_WIN') {
    	_("game_status").innerHTML = "你胜出啦";
    	gameStatus = 2;
    	alert("你胜出啦");
    }
    else if(cmd == 'YOU_LOSE') {
    	_("game_status").innerHTML = "你败北啦";
    	gameStatus = 2;
    	alert("你败北啦");
    }
    else if(cmd == 'CHAT') {
        _("chat").innerHTML += args[0] + ": " + args[1] + "<br/>";
        _("chat_end").scrollIntoView();
    }
	else if(cmd == 'ACK_INIT') {
		for(var i = 0; i < args.length; i += 3) {
			updateDesk(args[i], args[i+1], args[i+2]);
		}
	}
	else if(cmd == 'ACK_JOIN') {
		gDeskId = parseInt(args[0]);
		gUserId = parseInt(args[1]);
		var name = args[2];
		initDesk2DivMap(gDeskId);
		for(var i = 3; i < args.length; i += 3) {
			updateDesk(args[i], args[i+1], args[i+2]);
		}
		_('game_status').innerHTML = '请点击[我可以了]'
		var readyButton = createElement('input',['type', 'button', 'value', '我可以了',
		       'onclick', sprintf("send('READY,%d')", gDeskId)]);
		_('temp_pane').appendChild(readyButton);
		if(args.length == 3) { //the first user
			isFirstPlayer = true;
		}
		loop();
	}
	else if(cmd == 'ACK_JOIN_B') {
		var deskId = parseInt(args[0]);
		var name = args[1];
		updateDesk(deskId, name, '2');
	}
	else if(cmd == 'ACK_READY') {
		_('status').innerHTML = '好了';
		_('temp_pane').innerHTML = "";
		if(isFirstPlayer){
			_('game_status').innerHTML = '大家都好了请点[不等了开始吧]';
			var startBtn = createElement('input', ['type', 'button',
			     'value', '不等了开始吧', 'onclick', 'startGame();']);
			_('temp_pane').appendChild(startBtn);
		} else{
			_('game_status').innerHTML = '等待游戏开始';
		}
	}
	else if(cmd == 'ACK_READY_B') {
		var deskId = args[0];
		_('status_'+deskId).innerHTML = '好了';
	}
	else if(cmd == 'ACK_START'){
		gameStatus = 1;
		_('game_status').innerHTML = "等待分配角色";
		_('temp_pane').innerHTML = "";
		for(var i = 0; i < 8; i++){
			var statusDiv = _('status_'+i);
			if(statusDiv == null) continue;
			var ele = createElement('input', ['type', 'checkbox', 'id', 'check_' + i,
                                              'class', 'hidden']);
			statusDiv.innerHTML = "";
			statusDiv.appendChild(ele);
            _("selectable_" + i).setAttribute("onclick", "targetOnclick(" + i + ");");
		}
	}
	else if(cmd == 'SEAT_FULL'){
		alert('人满为患!');
	}
	else if(cmd == 'GAME_STARTED'){
		alert('游戏开始了，闲人免进');
	}
	else if(cmd == 'ASSIGN_ROLE'){
		var role = args[0];
		_('role').innerHTML = role;
		if(role == '主公'){
            _('role').className = 'role-zg';
			_('game_status').innerHTML = '请选择武将';
			showFigureChooser(args, 1, true);
		} else {
            if(role == '忠臣') {
                _('role').className = 'role-zc';
            } else if (role == '反贼') {
                _('role').className = 'role-fz';
            } else if (role == '内奸') {
                _('role').className = 'role-nj';
            }
			_('game_status').innerHTML = '等待主公选武将';
		}
	}
	else if(cmd == 'ASSIGN_FIGURE'){
		var deskId = args[0];
		_('game_status').innerHTML = '请选择武将';
		showFigureChooser(args, 1, false);
	}
	else if(cmd == 'ACK_SET_FIG'){
		var figName = args[0];
		var hp = args[1];
		_('game_status').innerHTML = '等待其他人选择武将';
		_('temp_pane').innerHTML = '';
		_('wj').innerHTML = args;
		_('hp').innerHTML = 'HP值   ' + hp;
	}
	else if(cmd == 'SHOW_OTHERS_FIGURE'){
		for(var i = 0; i < args.length; i+=2){
			var deskId = args[i];
			var figName = args[i+1][0];
			var hp = args[i+1][1];
			_('wj_'+deskId).innerHTML = args[i+1];
			_('hp_'+deskId).innerHTML = 'HP值   ' + hp;
		}
	}
	else if(cmd == 'SHOW_OTHERS_ROLE'){
		var deskId = args[0];
		var roleName = args[1];
		_('role_'+deskId).innerHTML = roleName;
	}
	else if(cmd == 'BROKE_RULE'){
		alert(args[0]);
	}
	else if(cmd == 'DIE'){
		var deskId = args[0];
		if(deskId == gDeskId){
			_('game_status').innerHTML = '你壮烈了';
			_('status').innerHTML = 'X';
			alert('你壮烈了');
		}else{
			_('status_'+deskId).innerHTML = 'X';
			alert(sprintf('玩家 [%s] 挂了', deskId));
		}
	}
	else if(cmd == 'REQ_SET_CARD'){
		showCardChooser(args);
		_('game_status').innerHTML = '请选择一张牌吧';
	}
	else if(cmd == 'NOTICE'){
		_('game_status').innerHTML = args[0];
	}
}

function cmdListHandler() {
    if(request.readyState == 4) {
        var cmds = eval('(' + request.responseText + ')');
        for(i in cmds) {
            cmdHandler(cmds[i]);
        }
    }
}

function loop() {
	if(gameStatus == 2)	return;
	mainLoopRequest = getXMLHttpRequest();
	var cmd = '/user?u_id='+gDeskId+'&_rand_='+Math.random();
	mainLoopRequest.open('GET', cmd, true);
	mainLoopRequest.onreadystatechange = mainLoopHandler;
	mainLoopRequest.send(null);
}

function mainLoopHandler() {
	if(mainLoopRequest.readyState == 4) {
		var cmds = eval('(' + mainLoopRequest.responseText + ')');
		for(i in cmds) {
			cmdHandler(cmds[i]);
		}
		loop();
	}
}

function updateDesk(deskId, userName, status){
	divId = desk2DivId[deskId];
    selectableDiv = createElement('div', ['id', 'selectable_'+deskId]);
	roleDiv = createElement('div', ['id', 'role_'+deskId, 'class', 'role']);
	roleDiv.innerHTML = '未知';
	nameDiv = createElement('div', ['id', 'name_'+deskId, 'class', 'name']);
	nameDiv.innerHTML = userName;
	statusDiv = createElement('div', ['id', 'status_'+deskId, 'class', 'status']);
	if( status == '1'){
		statusDiv.innerHTML = '好了';
	} else if(status == '2'){
		statusDiv.innerHTML = '观望';
	} else {
		alert('updateUserInfo: Unexpected arg value ' + status);
		return;
	}
	imageDiv = createElement('div', ['id', 'wj_'+deskId, 'class', 'image']);
	equipDiv = createElement('div', ['id', 'equip_'+deskId, 'class', 'equip']);
	div = createElement('div', ['class', 'equip-item', 'id', 'hp_'+deskId]);
	div.innerHTML = 'HP值';
	equipDiv.appendChild(div);
	div = createElement('div', ['class', 'equip-item', 'id', 'weapon_'+deskId]);
	div.innerHTML = '武器';
	equipDiv.appendChild(div);
	div = createElement('div', ['class', 'equip-item', 'id', 'defence_'+deskId]);
	div.innerHTML = '防具';
	equipDiv.appendChild(div);
	div = createElement('div', ['class', 'equip-item', 'id', 'horse_'+deskId]);
	div.innerHTML = '战马';
	equipDiv.appendChild(div);
	div = createElement('div', ['class', 'equip-item', 'id', 'judge_'+deskId]);
	div.innerHTML = '判定';
	equipDiv.appendChild(div);
	
	selectableDiv.appendChild(roleDiv);
	selectableDiv.appendChild(nameDiv);
	selectableDiv.appendChild(statusDiv);
	selectableDiv.appendChild(imageDiv);
	_(divId).appendChild(selectableDiv);
	_(divId).appendChild(equipDiv);
}

function showFigureChooser(args, startInd, isZG){
	var figureChooseDiv = createElement('div', ['id', 'fig_choice']);
	var choiceBtn = createElement('select', ['id', 'role_choice']);
	for(var i = startInd; i < args.length; i += 2){
		var figId = args[i];
		var figName = args[i+1];
		var opt = createElement('option', []);
		opt.value = figId; opt.text = figName;
		choiceBtn.add(opt, null);
	}
	figureChooseDiv.appendChild(choiceBtn);
	var cmdName = isZG ? "SET_ZG_FIG" : "SET_FIG";
	var cmd = sprintf('send("%s,%s," + _("role_choice").value)', cmdName, gDeskId)
	var btn = createElement('input', ['type', 'button', 'value', '选择', 'onclick', cmd]);
	figureChooseDiv.appendChild(btn);
	_('temp_pane').innerHTML = "";
	_('temp_pane').appendChild(figureChooseDiv);
}

function showCardChooser(args){
	var chooserDiv = createElement('div', []);
	var choiceBtn = createElement('select', ['id', 'card_choice']);
	for(var i = 0; i < args.length; i += 5){
		var cardId = args[i];
		var cardStr = args[i+1] + args[i+2] + args[i+3];
		var opt = createElement('option', []);
		opt.value = cardId; opt.text = cardStr;
		choiceBtn.add(opt, null);
	}
	chooserDiv.appendChild(choiceBtn);
	var cmd = 'send("SET_CARD,' + gDeskId + ',"+_("card_choice").value)';
	var btn = createElement('input', ['type', 'button', 'value', '选择', 'onclick', cmd]);
	chooserDiv.appendChild(btn);
	_('temp_pane').innerHTML = "";
	_('temp_pane').appendChild(chooserDiv);
}

function initDesk2DivMap(deskId){
	for(var i = 0; i < deskId; i++){
		desk2DivId[i] = deskId - i - 1;
	}
	for(var i = deskId; i < 7; i++){
		desk2DivId[i] = 7 - i + deskId;
	}
}

function showCard(cardAttrs){
	var cardId = cardAttrs[0];
	var cardDesc = cardAttrs[1] + cardAttrs[2] + cardAttrs[3];
	var div = createElement('div', ['id', 'card_'+cardId, 'class', 'card', 
		                                'onclick', 'cardOnclick(this.id);']);
	div.innerHTML = cardDesc;
	_('hand').appendChild(div);
}

function getSelectedDeskIds(){
    var checkedIds = []
	for(var i = 0; i < 8; i++){
		var e = _('check_'+i);
		if(e && e.checked)
            checkedIds.push(i);
	}
    return checkedIds;
}

function clearSelectedDeskIds() {
	for(var i = 0; i < 8; i++){
		var e = _('check_'+i);
        if(e) {
            e.checked = false;
        }
        e = _("selectable_" + i);
        if(e) {
            e.className = "";
        }
	}
}

function targetOnclick(id) {
    _("check_" + id).checked = !_("check_" + id).checked;
    _("selectable_" + id).className = _("check_" + id).checked? "selected": "";
}

function getSelectedCardIds() {
    return selectedCards;
}

function clearSelectedCardIds() {
    for(var i = 0; i < selectedCards.length; i ++) {
        if(_('card_' + selectedCards[i])) {
            _('card_' + selectedCards[i]).className = "card";
        }
    }
    selectedCards = new Array();
}

function cardOnclick(cardDivId) {
    cardId = cardDivId.slice("card_".length);
    for(var i = 0; i < selectedCards.length; i ++) {
        if(selectedCards[i] == cardId)
        {
            selectedCards.splice(i, 1);
            _(cardDivId).className = "card";
            return;
        }
    }
    selectedCards.push(cardId);
    _(cardDivId).className = "selected-card";
    debugCmd('$$ ', 'selectedCards', selectedCards);
}

function okOnClick() {
    var cardIds = getSelectedCardIds();
    var sendStr = "USE_CARD," + gDeskId + "," + cardIds;
    if(this.reqTargetWithCard) {
        var targetIds = getSelectedDeskIds();
        sendStr += "," + targetIds.join(",");
        debugCmd('$$ ', 'targetIds', targetIds);
    }
    send(sendStr);
    clearSelectedDeskIds();
    clearSelectedCardIds();
}

function cancelOnClick() {
    debugCmd('$$ ', 'Cancel clicked!', []);
    send("CANCEL," + gDeskId);
}
